'use strict';

let fs=require('fs');

let path=require('path');

let router=require('koa-router')();

function getfile() {
    let files=fs.readdirSync(__dirname);
    let resFiles=files.filter((filename)=>{
        return filename.endsWith('.js')&&filename!='index.js';
    })

    return resFiles;
}

function resignForEachFile(defaultPath,files) {
    files.forEach(element => {
        let tempPath=path.join(defaultPath,element);

        let routerObj=require(tempPath);

        for(let key in routerObj){
            let type=routerObj[key][0];
            let fn=routerObj[key][1];
            if(type==='get'){
                router.get(key,fn);
            }else if(type==='post'){
                router.post(key,fn);
            }
        }
    });
}

module.exports=function (dirPath) {
    let defaultPath=dirPath||__dirname;

    let files=getfile();

    resignForEachFile(defaultPath,files);

    return router.routes();
}